package com.hippo.core.exception;

import com.fasterxml.jackson.core.io.JsonEOFException;
import com.hippo.core.pojo.vo.result.BaseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingMatrixVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @ClassName GlobalException
 * @Description TODO 全局异常处理，错误码统一处理
 * @Author tangxl
 * @create 2023-05-09 16:32
 **/
@Slf4j
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Exception e){
        if(e instanceof HttpMessageNotReadableException){
            log.info("前端入参异常:{}", e.getMessage());
            e.printStackTrace();
            return BaseResult.fail("json解析异常");
        }
        if (e instanceof JsonEOFException){
            log.info("JSON格式错误:{}", e.getMessage());
            e.printStackTrace();
            return BaseResult.fail("JSON格式错误");
        }
        if (e instanceof HttpRequestMethodNotSupportedException){
            log.info("HTTP请求方式异常:{}", e.getMessage());
            e.printStackTrace();
            return BaseResult.fail("HTTP请求方式异常");
        }
        // 请求body参数异常处理，可以在实体属性上面添加注解@Range(min = 1, max = 10, message = "年龄只能在1-10岁之间")限制参数范围，也可以在controller层使用@Validated注解
        if (e instanceof MethodArgumentNotValidException) {
            log.info("调用方异常:{}", e.getMessage());
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            for (Object error : methodArgumentNotValidException.getBindingResult().getAllErrors()) {
                log.info("参数异常:" + error.toString());
                return BaseResult.fail(error.toString());
            }
        }
        // 请求param参数异常处理
        if(e instanceof MissingMatrixVariableException){
            log.info("调用方异常:{}", e.getMessage());
            MissingMatrixVariableException missingMatrixVariableException = (MissingMatrixVariableException) e;
            log.info("参数异常:" + missingMatrixVariableException.getVariableName()+"参数异常");
            return BaseResult.fail("参数异常："+missingMatrixVariableException.getVariableName()+"参数异常");
        }
        e.printStackTrace();
        return BaseResult.fail("系统处理异常");
    }
}
